using System;
using System.Collections.Generic;

namespace SqlQueryBuilder.Clauses
{
    /// <summary>
    /// And Clause
    /// </summary>
    public class And : IConditionalClause
    {
        private readonly IList<IConditionalClause> clauses = new List<IConditionalClause>();

        /// <summary>
        /// Initializes a new instance of the <see cref="And"/> class.
        /// </summary>
        /// <param name="conditionalClauses">The conditional cluses.</param>
        public And(params IConditionalClause[] conditionalClauses)
        {
            foreach (var clause in conditionalClauses)
            {
                clauses.Add(clause);
            }
        }

        /// <summary>
        /// Builds the where clause.
        /// </summary>
        /// <returns></returns>
        public string BuildConditionalClause()
        {
            return BuildClause();
        }

        /// <summary>
        /// Builds the clause.
        /// </summary>
        /// <returns></returns>
        private string BuildClause()
        {
            var andOperator = string.Empty;
            var result = string.Empty;
            foreach (var clause in clauses)
            {
                result += String.Format("{0}{1}", andOperator, clause.BuildConditionalClause());
                if (string.IsNullOrEmpty(andOperator)) andOperator = " AND ";
            }
            return string.Format("({0})", result);
        }
    }
}